package top.fyxxxx.dbdesign.servlet;

import top.fyxxxx.dbdesign.dao.DBoperate;
import top.fyxxxx.dbdesign.data.SignInRecord;
import top.fyxxxx.dbdesign.data.SignInTask;
import top.fyxxxx.dbdesign.util.SignInModule;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/SignInServlet")
public class SignInServlet extends HttpServlet implements SignInModule {
    DBoperate dBoperate=DBoperate.getInstance();
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        HttpSession session=request.getSession(true);
        long uid= (Long) session.getAttribute("uid");
        String sid=request.getParameter("sid");
        if(sid==null||!isdigit(sid)){
            fail(request,response,0);return;
        }
        if(signin(uid,Long.parseLong(sid)))success(request,response,Long.parseLong(sid));
        else fail(request,response,Long.parseLong(sid));
    }
    private boolean isdigit(String s){
        for(char c:s.toCharArray()){
            if(c>'9'||c<'0')return false;
        }
        return true;
    }
    private void fail(HttpServletRequest request, HttpServletResponse response,long sid) throws IOException {
        response.sendRedirect("signin.jsp?sid="+sid);
    }
    private void success(HttpServletRequest request, HttpServletResponse response,long sid) throws IOException {
        response.sendRedirect("signin.jsp?sid="+sid);
    }
    @Override
    public boolean signin(long uid, long sid) {
        SignInTask task=dBoperate.getSignInTask(sid);
        //时间已过
        if(task.getEndTime()<System.currentTimeMillis()||
                task.getBeginTime()>System.currentTimeMillis()) return false;
        //已签到
        if(dBoperate.getSignInRecord(uid,sid).getSdate()!=0)return true;
        long cid=task.getBelongToCid();
        SignInRecord record=new SignInRecord(uid,cid,sid,System.currentTimeMillis());
        dBoperate.insertSignin(record);
        return true;
    }
}
